﻿using BBCore.Core.Models.Samples;
using BBCore.Infrastructure.Helps;
using BootstrapBlazor.Components;
using ClosedXML.Excel;
using DocumentFormat.OpenXml.Spreadsheet;
using FluentValidation;
using Magicodes.ExporterAndImporter.Core;
using Magicodes.ExporterAndImporter.Excel;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.JSInterop;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;

namespace BBCore.Server.Components.Pages.Samples
{
    /// <summary>
    /// 主从明细弹窗批量保存示例
    /// </summary>
    public partial class HYJ_Master_Details_Modal
    {
        [Parameter]
        [NotNull]
        public HYJ_Master_Table? Model { get; set; }
        [Parameter]
        public Action<DialogResult>? OnSaveSuccess { get; set; }
        [CascadingParameter]
        [NotNull]
        private Modal? Modal { get; set; }
        /// <summary>
        /// 保存初始数据的 JSON 字符串
        /// </summary>
        private string? initialModelJson;
        /// <summary>
        /// 查询框
        /// </summary>
        private string searchQuery = "";
        protected override async Task OnInitializedAsync()
        {
            await base.OnInitializedAsync();
            if (Model != null)
            {
                initialModelJson = JsonSerializer.Serialize(Model);
            }
        }

        private List<HYJ_Detail_Table> FilteredDetails
        {
            get
            {
                if (Model.Details == null)
                {
                    return new List<HYJ_Detail_Table>();
                }
                if (string.IsNullOrEmpty(searchQuery))
                {
                    return Model.Details;
                }
                return Model.Details.Where(d =>
                    (d.ITEM != null && d.ITEM.Contains(searchQuery, StringComparison.OrdinalIgnoreCase)) ||
                    (d.LEVEL2 != null && d.LEVEL2.Contains(searchQuery, StringComparison.OrdinalIgnoreCase))
                ).ToList();
            }
        }
        private void ClearSearchQuery()
        {
            searchQuery = "";
            StateHasChanged();
        }
        private async Task ShowConfirmation()
        {
            var result = await JSRuntime.InvokeAsync<bool>("confirm", "确定要重置吗？");
            if (result)
            {
                ResetData();
            }
        }
        /// <summary>
        /// 重置
        /// </summary>
        private void ResetData()
        {
            if (!string.IsNullOrEmpty(initialModelJson))
            {
                Model = JsonSerializer.Deserialize<HYJ_Master_Table>(initialModelJson);
                searchQuery = ""; // 清空搜索框
                StateHasChanged();
            }
        }

        private async Task OnValidSubmit(EditContext context)
        {
            try
            {
                var items = (HYJ_Master_Table)context.Model;
                if (items.HEAD_ID == 0)//新增
                {
                    using var uow = freeSql.CreateUnitOfWork();//开启单元测试事务
                    var repo = freeSql.GetRepository<HYJ_Master_Table>();
                    repo.UnitOfWork = uow;//手工绑定工作单元
                    repo.DbContextOptions.EnableCascadeSave = true;//开启级联保存功能
                    repo.Insert(items);
                    uow.Commit();//事务提交,异常会自动回滚
                    await ShowToastMessageAsync("新增保存数据成功", ToastCategory.Success);
                }
                else
                {
                    using var uow = freeSql.CreateUnitOfWork();//开启单元测试事务
                    var repository = freeSql.GetAggregateRootRepository<HYJ_Master_Table>();
                    repository.UnitOfWork = uow;//手工绑定工作单元
                    var dataDetails = repository.Select.Where(a => a.HEAD_ID == items.HEAD_ID).First(); //此时已自动 Attach            
                    dataDetails = items;
                    repository.Update(dataDetails);
                    uow.Commit();//事务提交,异常会自动回滚
                    await ShowToastMessageAsync("更新保存数据成功", ToastCategory.Success);
                }
                await OnClose(DialogResult.Yes);

            }
            catch (Exception ex)
            {
                await ShowSwalMessageAsync("出错信息:" + ex.Message, SwalCategory.Error);
            }
        }
        [NotNull]
        private BootstrapInput<string?>? _newInputRef { get; set; }
        private void AddNewRow()
        {
            Model.Details?.Add(new HYJ_Detail_Table());
            Task.Run(async () =>
            {
                await Task.Delay(50);
                await _newInputRef.FocusAsync();
            });
        }
        private async Task<bool> OnBatchDeleteAsync(IEnumerable<HYJ_Detail_Table> items)
        {

            foreach (var item in items)
            {
                Model.Details?.Remove(item);
            }
            return await Task.FromResult(true);
        }
        public async Task OnClose(DialogResult result)
        {
            if (result == DialogResult.Yes)
            {
                OnSaveSuccess?.Invoke(DialogResult.Yes);//通知父组件保存成功了
                await Modal.Close();//关闭弹窗
            }
            await Task.CompletedTask;
        }
        public async Task ExportByTemplate()
        {
            //添加个异常处理,如果发布到iis提示文件夹没权限,在文件夹下添加Authenticated Users并添加相应的权限
            //var data = await freeSql.Select<HYJ_Master_Table>().Where(a => a.HEAD_ID == Model.HEAD_ID).IncludeMany(a => a.Details).ToListAsync();
            //模板路径
            var tplPath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "ExcelFiles", "ExcelTemplate","主从明细表导出模板.xlsx");
            //创建Excel导出对象
            IExportFileByTemplate exporter = new ExcelExporter();
            //导出路径
            var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "ExcelFiles", "ExcelTemplate", "主从明细表测试.xlsx");
            //根据模板导出
            await exporter.ExportByTemplate(filePath, Model, tplPath);
        }
    }
}
